var relationAPI=require('../../api/Relation')
var userAPI=require('../../api/User')
var scoreAPI=require('../../api/Score')
var appJs=require('../../app')
const app=getApp()
let SCREEN_WIDTH = 750
let RATE = wx.getSystemInfoSync().screenHeight /wx.getSystemInfoSync().screenWidth
Page({
data:{
  ScreenTotalW: SCREEN_WIDTH,
  ScreenTotalH: SCREEN_WIDTH * RATE,
  currentIcon:'./images/user/smile.svg',
  scoreList:[],
  totalScore:0,
  relation:[],
  currentUserCode:'0',//当前用户code 0表示自己1表示对方
  nickName: '',
  apiTypeCode: 0,       // 0 为 调用增加接口 ,1为调用修改接口
  scoreForm: {
    scoreAlert:'',
    "scoreId": "",        //后端生成
    "type": "1",         //暂时默认为1表示加分 -1表示扣分
    "userId": "",        //后端处理
    "relationId": "3e3304f9900a11ed848bb8599f3a5d50",//接口传入
    "score": 1,  //表单传入
    "reason": ""//表单传入
  },
  isHiddenRecordDetail: true,
},
  onLoad:async  function(options) {
    var _this=this
    // 初始化云托管
    if (!wx.cloud) {
      console.error('请使用 2.2.3 以上版本的基础库');
    } else {
      wx.cloud.init({
        env: 'prod-3gfrot0nb41198bc'
      })
    }
    await app.login()
  

//  改变昵称和头像
   await this.changeIConAndNick()

    // 查询关系和积分
   await _this.changeScoreList()
    if(options.relation!=null){
      var relation= JSON.parse(options.relation)
      console.log(_this.showModalAndHanle)
       _this.showModalAndHanle('情侣关系建立','确认和对方建立情侣关系吗','接受','拒绝',()=>{
        relation.receiverId= wx.getStorageSync('userId')
        console.log( relation.receiverId)
        relationAPI.updateRelation(relation).then((res)=>{
          _this.changeScoreList()
        })
       },()=>{
        
         relationAPI.deleteRelation(relation.relationId).then((res)=>{
          // this.setData({nickName: JSON.stringify(res)}) 
         })
        })
    }
  },
  onShow:async  function(){
    // await this.onLoad()
    await  this.changeIConAndNick()
    await  this.changeScoreList()
  }
  ,
  navigationToMore: function () {
    wx.navigateTo({
      url: '/pages/more/index',
    })
  },
  // 改变加分悬浮框的可见性
  changeRecordDetailVisibile: function () {
   var _this=this
    if(_this.data.relation[0]!=null){
      this.setData({isHiddenRecordDetail:this.data.isHiddenRecordDetail==true?false:true})
    }else{
      wx.showToast({
        title: '情侣关系未建立',
        icon: 'error',
        duration: 2000
      })
    }
     
  },
  // 改变当前用户状态码,更新头像
  changeUserCode: function () {
    var _this =this
    if(_this.data.relation[0]==null){
      wx.showToast({
        title: '情侣关系未建立',
        icon: 'error',
        duration: 2000
      })
      return
    }
    if(this.data.currentUserCode==0){//用户状态由自己转换到对方
      this.setData({currentUserCode:'1',
                     currentIcon:app.data.loverUser.iconUrl                            
    })
 
    }else{
      this.setData({currentUserCode:'0',
          currentIcon:app.data.currentUser.iconUrl             
})
    }
    console.log('当前用户头像地址')
    console.log(this.data.currentIcon)
    this.changeScoreList()
  },
 
  showModalAndHanle:function (title,content,confirmButtonText,cancelButtonText,resoleve,reject) {
    wx.showModal({
      title: title,
      content: content,
      confirmText:confirmButtonText,
      cancelText: cancelButtonText,
      success(res) {
        // console.log(res)
        //如果用户点击了确定按钮
        if (res.confirm) {
           resoleve()
          // _this.getUserProfileInfo()
        } else if (res.cancel) {
          //如果用户点击了取消按钮
          reject()
          return;
        }
      }
    });
  }
  ,
  getUserProfileInfo:function () {
    wx.getUserProfile({
      desc: '获取你的昵称、头像、地区及性别',
      success: res => {
        _this.setData({
          // iconUrl:res.userInfo.avatarUrl,
                        // nickName:res.userInfo.nickName,
                        })                
       _this.login()
      },
      fail: res => {
        // console.log(2)
        // console.log(res)
        //拒绝授权
        wx.showToast({
          title: '您拒绝了请求,不能正常使用小程序',
          icon: 'error',
          duration: 2000
        });
        return;
      }
    });
  }
  ,
  //填充关系和补充积分并返回切片数组
  changeScoreList: function () 
    {
    var _this=this
    relationAPI.getRelation().then((res)=>{
      _this.setData({relation:[res.data.result[0]]})
      //  console.log(this.data.relation[0])
      if(_this.data.relation[0]==null)return[]
     }).then(()=>{
     if(_this.data.relation[0]!=null){
       scoreAPI.getScore(_this.data.relation[0].relationTypeId,this.data.currentUserCode,1,10000).then((res)=>{
         
        //  计算总积分
        var scoreList=res.data.result.scoreList
        var count=0
        for(let i in scoreList){
          console.log(scoreList[i])
          if(scoreList[i].type='1')count+=scoreList[i].score
          else count-=scoreList[i].score
        }
        console.log(count)
        // 切片注入页面需要的数据
        _this.setData({scoreList:scoreList.slice(0,5),
           totalScore:count})
       }).catch((error)=>{
         console.log(error)
        })
     }})
  },
 
  // 调用后端接口添加积分
  addScore:function () {
    scoreAPI.addScore(scoreForm)
  },
  // socre 进行检查
  checkfenzhi:function (e) {
    var score=e.detail.value
  var   scoreNum= Number(score)
  var scoreForm=this.data.scoreForm
  if(!(scoreNum===scoreNum)){
    console.log('请输入数字')
    scoreForm.score=1
    scoreForm.scoreAlert='请输入积分数字'
    this.setData(scoreForm)
  }else if(scoreNum==2000){
    scoreForm.score=1
    scoreForm.scoreAlert='不可以色色'
   this.setData(scoreForm)
    console.log('不可以色色')
  }else{//结果正常
    scoreForm.score=scoreNum
    this.setData(scoreForm)
    console.log('获取到值')
    console.log(scoreNum)
  }

 
  },
  // 对reason进行检查
  checkReason:function (e) {
   var reason=e.detail.value
   this.data.scoreForm.reason=reason
  //  console.log(reason)   
  },

  // add和update点击后的触发事件
  postOrUpdateScore:function () {
  //  填充relationId
  var relationId=this.data.relation[0].relationId
    this.data.scoreForm.relationId=relationId 
    console.log(this.data.scoreForm)
    this.data.scoreForm.type='1'
    if(this.data.apiTypeCode=='0'){
      scoreAPI.addScore(this.data.scoreForm).then((res)=>{
        console.log(res)
})
    }else{
      scoreAPI.updateScore(this.data.scoreForm).then((res)=>{console.log(res)}).catch((error)=>{console.log(error)})
    }
    this.changeRecordDetailVisibile()
    this.changeScoreList()
  },
  // 点击某条记录进行回显
  showDetail:function (event) {
    // event.currentTarget.
   var tarId=event.currentTarget.dataset.scoreid
   var scoreList=this.data.scoreList
   console.log(scoreList)
    for(let i in scoreList){
      console.log('寻找结果')
       if(scoreList[i].scoreId==tarId){
         console.log('成功命中id')
         console.log(scoreList[i])
           // 绑定开发事件
    this.changeScoreModeToUpdate()
         this.setData({
        scoreForm:scoreList[i]
       })
         
       }
    }

    // 打开悬浮框
      this.changeRecordDetailVisibile()
  },
  // 打开加分之前的初始操作
  showAdd:function () {
    this.setData({
      apiTypeCode: '0',
      scoreForm:{
        score: 1,
        reason: ''
      }
    })
    this.changeRecordDetailVisibile()
  }
  ,
  // 改变apiType状态码为0
  changeScoreModeToAdd:function () {
     this.setData({apiTypeCode:0})
  },
  // 改变apiType状态码为1
  changeScoreModeToUpdate:function () {
    this.setData({apiTypeCode:1})
  },
  deleteScore:function (event) {
  var scoreId=event.currentTarget.dataset.scoreid
    // console.log(event.currentTarget.dataset.scoreid)
    if(this.data.currentUserCode=='1'){
      scoreAPI.deleteScore(scoreId).then(async (res)=>{
        await this.changeScoreList()
        await this.changeRecordDetailVisibile()
       })
    }  

  },
  onShareAppMessage:async function () {
   var relation= {
    "relationId": "",
    "initiatorId": "",//发起者id
    "receiverId": "",
    "relationTypeId": "123123",//情侣类型
    "relationStatus": ""
}
// 请求接口初始化relation对象
   await userAPI.getUserInfo().then((res)=>{ 
     console.log(res.data.result)
    relation.initiatorId=res.data.result.id
    console.log(res.data.result.id)
    console.log(JSON.stringify(relation))
    // this.setData({nickName:JSON.stringify(relation)})
  })
 
  // 添加relation记录
  var res=await relationAPI.addRelation(relation).then((res)=>{
    console.log(res)
    // _this.setData({nickName:res.data.result[0].relationId})
    if(res.data.code==4000){
       wx.showToast({
         title:'请求待对方同意',
         icon: 'error'
       })
    }
    relation.relationId=res.data.result[0].relationId
    return res
  })
 

    // console.log('./index.wxml'+'?relation='+JSON.stringify(relation))
    
    return {
      title:'快来和我成为世界上最甜蜜的恋人',
      path:'/pages/index/index?relation='+JSON.stringify(relation)
    }
 },
   changeIConAndNick:async function(){
   var res=await userAPI.getUserInfo()
  //  .then((res)=>{
      // console.log(res)
      // console.log(res.data.result.avatar)
      // app.data.currentUser.iconUrl=res.data.result.avatar
      // this.setData({nickname:res.data.result.nickname,                                           
      //              currentIcon:res.data.result.avatar,
      //               iconUrl:res.data.result.avatar,
                  //  }
    // )
  // })
  console.log(res)
  app.data.currentUser.iconUrl=res.data.result.avatar
   this.setData({nickname:res.data.result.nickname,                                           
                   currentIcon:res.data.result.avatar,
                    iconUrl:res.data.result.avatar,
                   }
    )
    console.log(res)
    await userAPI.getConnectedUserInfo().then((res)=>{
      console.log(res.data.result.avatar)
    if(res.data.result.avatar!=null){
      app.data.loverUser.iconUrl=res.data.result.avatar
      console.log(app.data.currentUser.iconUrl)
      console.log( app.data.loverUser.iconUrl)
      
      // _this.setData({iconUrl_lover:res.data.result.avatar})
    }
    })
   }
});



